package config;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 读取xml配置文件的类
 */
public class XmlConfig {

    /**
     * 读取配置文件
     * @param path
     * @return
     */
    public static Map<String,Bean> getConfig(String path){
        Map<String,Bean> configMap = new HashMap<String,Bean>();
        //使用dom4j和xpath读取xml文件
        Document doc = null;
        SAXReader reader = new SAXReader();
        InputStream in = XmlConfig.class.getResourceAsStream(path);
        try {
            doc = reader.read(in);
        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException("配置文件地址不对");
        }
        //定义xpath，取出所有的bean
        String xpath = "//bean";
        //遍历所有bean
        List<Element> list = doc.selectNodes(xpath);
        if(list!=null){
            for(Element beanEle : list){
                Bean bean  = new Bean();
                //bean节点的id
                String id = beanEle.attributeValue("id");
                //class属性
                String className = beanEle.attributeValue("class");
                bean.setId(id);
                bean.setClassName(className);

                //获取bean节点下所有的property节点
                List<Element> proList = beanEle.elements();
                if(proList!=null){
                    for (Element proEle : proList) {
                        Property prop = new Property();
                        String propName = proEle.attributeValue("name");
                        String propValue = proEle.attributeValue("value");
                        String propRef = proEle.attributeValue("ref");
                        //封装到property属性中
                        prop.setName(propName);
                        prop.setValue(propValue);
                        prop.setRef(propRef);

                        bean.getProperties().add(prop);
                    }
                    //id 不能重复
                    if(configMap.containsKey(id)){
                        throw new RuntimeException(id+"bean节点重复");
                    }

                    configMap.put(id,bean);
                }
            }
        }
        return configMap;
    }
}
